package dao

import (
	"database/sql"
	"log"
)

const TableEvalute = "evaluate"

const LabelZan = "1"
const LabelHei = "2"
const LabelCai = "3"

/*
 * 添加评论
 */
func (dbw *DbWorker) EvaluateAdd(company_id, content, label_type, ip string) bool {
	dbw.MysqlConnect()
	defer dbw.Db.Close()

	sql, err := dbw.Db.Prepare("insert into " + TableEvalute + " (company_id, content, label_type, ip) values(?, ?, ?, ?)")
	if err != nil {
		log.Fatal(err)
		panic(err.Error())
	}
	sql.Exec(company_id, content, label_type, ip)
	return true
}

func (dbw *DbWorker) EvaluteUpdate(company_id, content, label_type, ip string) bool {
	return true
}

func (dbw *DbWorker) EvaluteDelete(id string) bool {
	dbw.MysqlConnect()
	defer dbw.Db.Close()

	sql, err := dbw.Db.Prepare("delete from " + TableEvalute + " where id=?")
	if err != nil {
		log.Fatal(err)
		panic(err.Error())
	}
	sql.Exec(id)
	return true
}

/*
 * 统计评价意向
 */
func (dbw *DbWorker) EvaluteNumbers(company_id string) map[string]string {
	dbw.MysqlConnect()
	defer dbw.Db.Close()

	rows, err := dbw.Db.Query(
		"select label_type,count(1) star from "+TableEvalute+" where company_id=? group by label_type",
		company_id)

	if err != nil {
		log.Fatal(err)
		panic(err.Error())
	}
	defer rows.Close()

	var numbers = map[string]string{
		LabelZan: "0",
		LabelHei: "0",
		LabelCai: "0",
	}

	columns, err := rows.Columns()
	values := make([]sql.RawBytes, len(columns))
	scanArgs := make([]interface{}, len(values))
	for i := range values {
		scanArgs[i] = &values[i]
	}

	for rows.Next() {
		err = rows.Scan(scanArgs...)
		if err != nil {
			log.Fatal(err)
			panic(err.Error())
		}

		numbers[string(values[0])] = string(values[1])
	}
	return numbers
}

/*
 * 计数公司评论条数
 */
func (dbw *DbWorker) EvaluteCount(company_id string) string {
	dbw.MysqlConnect()
	defer dbw.Db.Close()

	var num string

	err := dbw.Db.QueryRow("select count(1) num from "+TableCompany+" where id=?", company_id).Scan(&num)
	if err != nil {
		panic(err.Error())
	}
	return num
}

func (dbw *DbWorker) EvaluteRows(company_id string) []map[string]string {
	dbw.MysqlConnect()
	defer dbw.Db.Close()

	sql_str := "select * from " + TableEvalute + " where company_id=? order by id desc"

	rows, err := dbw.Db.Query(sql_str, company_id)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	columns, err := rows.Columns()
	if err != nil {
		log.Fatal(err)
	}
	values := make([]sql.RawBytes, len(columns))
	scanArgs := make([]interface{}, len(values))
	for i := range values {
		scanArgs[i] = &values[i]
	}

	u := make([]map[string]string, 0)
	for rows.Next() {
		err = rows.Scan(scanArgs...)
		if err != nil {
			panic(err.Error())
		}

		var value string
		var m = map[string]string{}
		for i, col := range values {
			if col == nil {
				value = ""
			} else {
				value = string(col)
			}
			m[columns[i]] = value
		}
		u = append(u, m)
	}
	return u
}
